package com.drodds.game;

/*
//imports for FPS statistics
import java.text.DecimalFormat;
import java.util.logging.Logger;
*/
import android.graphics.Canvas;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;

public class DrawThread extends Thread {
	private static final String TAG = DrawThread.class.getSimpleName();
	
	private final static int MAX_FPS = 60;
	private final static int MAX_FRAME_SKIPS = 5;
	private final static int FRAME_PERIOD = 1000 / MAX_FPS;

/*
	//FPS Statistics vars
	private DecimalFormat df = new DecimalFormat("0.##");
	private final static int STAT_INTERVAL = 1000;
	private final static int FPS_HISTORY_NR = 10;
	private long lastStatusScore = 0;
	private long statusIntervalTimer = 01;
	private long totalFramesSkipped = 01;
	private long framesSkippedPerStatCycle = 01;
	private int frameCountPerStatCycle = 0;
	private long totalFrameCount = 01;
	private double fpsStore[];
	private long statsCount = 0;
	private double averageFps = 0.0;
*/
	
	private boolean running;
	private SurfaceHolder surfaceHolder;
	private GameEngine gameEngine;
	
	public Handler handler;
	
	public DrawThread(SurfaceHolder sh, GameEngine gEng) {
		this.surfaceHolder = sh;
		this.gameEngine = gEng;
	}
	
	public void setRunning(boolean r) {
		this.running = r;
	}
	
	@Override
	public void run() {
		Canvas canvas;
		//for FPS calculations statistics
		//initTimingElements();
		
		long beginTime;
		long timeDiff = 0;
		int sleepTime;
		int framesSkipped;
		
		sleepTime = 0;
		
		while (running) {
			canvas = null;
			try {
				canvas = this.surfaceHolder.lockCanvas();
				synchronized(surfaceHolder) {
					beginTime = System.currentTimeMillis();
					framesSkipped = 0;
					this.gameEngine.update(timeDiff/1000.0f);
					if (canvas != null)
						this.gameEngine.draw(canvas);
					
					timeDiff = System.currentTimeMillis() - beginTime;
					sleepTime = (int)(FRAME_PERIOD - timeDiff);
					
					if (sleepTime > 0) {
						try {
							Thread.sleep(sleepTime);
						}
						catch(InterruptedException e) {
						}
					}
					
					while (sleepTime < 0 && framesSkipped < MAX_FRAME_SKIPS) {
						this.gameEngine.update(FRAME_PERIOD/1000.0f);
						sleepTime += FRAME_PERIOD;
						framesSkipped++;
					}
					
					if (framesSkipped > 0) {
						Log.d(TAG, "Skipped:" + framesSkipped);
					}
					
					//statistics
					/*framesSkippedPerStatCycle += framesSkipped;
					storeStats();
					*/
				}
			}
			finally {
				if (canvas != null) {
					surfaceHolder.unlockCanvasAndPost(canvas);
				}
			}
		}
	}
	
/*
 	//FPS Statistics Calculations
	private void storeStats() {
		frameCountPerStatCycle++;
		totalFrameCount++;

		// check the actual time
		statusIntervalTimer += (System.currentTimeMillis() - statusIntervalTimer);

		if (statusIntervalTimer >= lastStatusStore + STAT_INTERVAL) {
			// calculate the actual frames pers status check interval
			double actualFps = (double)(frameCountPerStatCycle / (STAT_INTERVAL / 1000));

			//stores the latest fps in the array
			fpsStore[(int) statsCount % FPS_HISTORY_NR] = actualFps;

			// increase the number of times statistics was calculated
			statsCount++;

			double totalFps = 0.0;
			// sum up the stored fps values
			for (int i = 0; i < FPS_HISTORY_NR; i++) {
				totalFps += fpsStore[i];
			}

			// obtain the average
			if (statsCount < FPS_HISTORY_NR) {
				// in case of the first 10 triggers
				averageFps = totalFps / statsCount;
			} else {
				averageFps = totalFps / FPS_HISTORY_NR;
			}
			// saving the number of total frames skipped
			totalFramesSkipped += framesSkippedPerStatCycle;
			// resetting the counters after a status record (1 sec)
			framesSkippedPerStatCycle = 0;
			statusIntervalTimer = 0;
			frameCountPerStatCycle = 0;

			statusIntervalTimer = System.currentTimeMillis();
			lastStatusStore = statusIntervalTimer;
//			Log.d(TAG, "Average FPS:" + df.format(averageFps));
			gamePanel.setAvgFps("FPS: " + df.format(averageFps));
		}
	}

	private void initTimingElements() {
		// initialise timing elements
		fpsStore = new double[FPS_HISTORY_NR];
		for (int i = 0; i < FPS_HISTORY_NR; i++) {
			fpsStore[i] = 0.0;
		}
		Log.d(TAG + ".initTimingElements()", "Timing elements for stats initialised");
	}
*/
}
